package com.binfenhulian.chinaenergy.ces.manage.controller.common;

import com.binfenhulian.chinaenergy.ces.core.bean.result.AjaxResult;
import com.binfenhulian.chinaenergy.ces.manage.core.oss.service.OSSService;
import com.binfenhulian.chinaenergy.ces.utils.random.RandomGUIDUtil;
import com.binfenhulian.chinaenergy.ces.utils.string.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;

@Controller
@RequestMapping("/common")
public class CommonController {

    @Resource(name = "com.binfenhulian.chinaenergy.ces.manage.core.oss.service.OSSServiceImpl")
    private OSSService ossService;

    //上传文件
    @RequestMapping("/file/upload")
    @ResponseBody
    public Object uploadFile(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws Exception {
        String dir = request.getParameter("dir");
        byte[] bytes = file.getBytes();
        String key;
        if (StringUtils.isEmpty(dir)) {
            key = ossService.upLoadFile(bytes);
        } else {
            key = dir + RandomGUIDUtil.getRawGUID();
            ossService.upLoadFile(key, bytes);
        }
        String url = ossService.getTempAccessUrl(key);
        HashMap map = new HashMap();
        map.put("key", key);
        map.put("url", url);
        return new AjaxResult(200, "", true, map);
    }
}
